package models.campus;

import models.UUIDModel;
import models.admin.AdminUser;
import models.constants.DeletedStatus;
import play.db.jpa.JPA;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

/**
 * 楼宇
 */
@Entity
@Table(name = "bd_buildings")
public class Building extends UUIDModel {

    /**
     * 所属小区
     */
    @JoinColumn(name = "campus_id")
    @ManyToOne
    public Campus campus;

    /**
     * 楼宇名称
     */
    @Column(name = "name", length = 10)
    public String name;

    /**
     * 联系电话
     */
    @Column(name = "phone", length = 15)
    public String phone;


    /**
     * 备注信息
     */
    @Column(name = "remark", length = 100)
    public String remark;


    public Building(){};

    public Building(Campus campus , String name , AdminUser loginUser){
        this.campus = campus;
        this.name = name;
        this.deleted = DeletedStatus.UN_DELETED;
        this.createdAt = new Date();
        this.createUser = loginUser  ;
        this.belongCompany = loginUser.organization != null  ? loginUser.organization : null;
    }
    /**
     * 查询园区的楼宇
     *
     * @param campusId
     * @return
     */
    public static List<Building> findBycampus(String campusId) {
        return Building.find(" campus.id = ? and deleted = ? order by name ", campusId , DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * @param id
     * @return
     */
    public static Building findByBuildingId(String id) {
        return Building.find(" id = ? and deleted = ?", id , DeletedStatus.UN_DELETED).first();
    }

    /**
     * @param delIds
     */
    public static void deleteBuilding(String[] delIds) {
        String delIdStr = UStringUtil.concatStr("','", delIds);
        delIdStr = "'" + delIdStr + "'";
        String sqlDelete = "update  bd_buildings  a set a.deleted = 1 where a.id  in (" + delIdStr + ")";
        JPA.em().createNativeQuery(sqlDelete).executeUpdate();
    }

    /**
     *
     * @param id
     * @return
     */
    public static Boolean checkIsUsed(String id){
        long areas = Area.count("building.id = ? and deleted = 0",id);
        long floors = Floor.count("building.id = ? and deleted = 0",id);
        long rooms = Room.count("building.id = ? and deleted = 0",id);
        if(areas > 0 || floors > 0 || rooms > 0)
            return true ;

        return false;
    }

    /**
     * 根据物业 ,楼宇名称查询
     * @param campus
     * @param buildingName
     * @return
     */
    public static  Building findByNameAndCampus( Campus campus ,String buildingName){
        return Building.find(" deleted = ? and name = ? and campus = ?" , DeletedStatus.UN_DELETED ,buildingName , campus).first() ;
    }
}
